package com.example.chat04.config;

import com.example.chat04.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.Objects;
import java.util.Optional;

@Component
public class WebSocketEventListener {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Value("${redis.set.onlineUsers}")
    String onlineUsers;
    @Value("${redis.channel.msgToAll}")
    String msgToAll;

    /**
     * 监听连接的处理
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        logger.info("Received a new web socket connection,用户名: {}", event.getUser() != null ? event.getUser().getName() : "不存在");
    }

    /**
     * 监听连接断开的处理
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionDisconnectEvent event) {
//        StompHeaderAccessor.wrap(event.getMessage());
        StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(event.getMessage(), StompHeaderAccessor.class);
        String username = (String) accessor.getSessionAttributes().get("username");
        if (username != null) {
            logger.info("User Disconnected : " + username);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(ChatMessage.MessageType.LEAVE);
            chatMessage.setSender(username);

            //simpMessagingTemplate.convertAndSend("/topic/chat.public", chatMessage);
            try {
                // 从redis删除该用户
                redisTemplate.opsForSet().remove(onlineUsers,username);
                // 把离开的消息发送到redis
                redisTemplate.convertAndSend(msgToAll,chatMessage);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }

        }
    }

}
